from datetime import datetime

from flask_login import UserMixin

from . import db
from . import login_manager

class UserInfo(UserMixin, db.Model):
    __tablename__ = 'user_info'
    id = db.Column(db.Integer, primary_key=True)
    screenname = db.Column(db.String(64))
    desc = db.Column(db.String(200))
    oauths = db.relationship('OAuth', backref='userinfo')
    posts = db.relationship('Posts', backref='userinfo')

    def __repr__(self):
        return '<UserInfo %r>' % self.screenname

    def binded(self, oauth_name, user_id):
        oauth = OAuth.query.filter_by(oauth_name=oauth_name, user_id=user_id).first()
        if oauth:
            return True
        else:
            return False


class OAuth(db.Model):
    __tablename__ = 'oauth'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user_info.id'))
    oauth_name = db.Column(db.String(20))
    oauth_id = db.Column(db.String(64))
    oauth_access_token = db.Column(db.String(128))
    oauth_refresh_token = db.Column(db.String(128))
    oauth_expire = db.Column(db.Integer)

    def __repr__(self):
        return '<OAuth %r>' % self.oauth_name


class Posts(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user_info.id'))
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    gift_id = db.Column(db.Integer)

    def __repr__(self):
        return '<Posts %r>' % self.id


@login_manager.user_loader
def load_user(user_id):
    return UserInfo.query.get(int(user_id))
